package com.ruoyi.wechat.controller;

import cn.hutool.core.lang.Validator;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.tool.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/wechat/verification")
public class VerificationCode {

    private final String VALIDATION="verification";


    @Autowired
    private RedisCache redisCache;

    @Anonymous
    @PostMapping("/sendCode")
    public AjaxResult sendMsg(@RequestParam("phone") String phone) {
        try {
            if (send(phone)){
                return AjaxResult.success();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.error("验证码发送失败");
    }

    public Boolean send(String phone) {
        if (Validator.isMobile(phone)) {
            String verificationCode = generateVerificationCode(6);
            String[] phonearr = {phone};
            String[] params = {verificationCode, RuoYiConfig.getSmsTime()};
            try {
                // TODO:需要完成的功能
                SmsSingleSenderResult sms = SmsUtil.SMS(phonearr, params, Integer.valueOf(RuoYiConfig.getSmsAppId()), RuoYiConfig.getSmsAppKey(), Integer.valueOf(RuoYiConfig.getSmsTemplateId()), RuoYiConfig.getSmsSign());
                System.out.println(sms);
                // 设置缓存5分钟过期
                redisCache.setCacheObject(getPhoneKey(phone), verificationCode, 5, TimeUnit.MINUTES);
                return true;
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (HTTPException e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }


    @Anonymous
    @PostMapping("/verificationCode")
    public AjaxResult verificationCode(@RequestParam("phone") String phone, @RequestParam(value = "verificationCode") String verificationCode) {
        String code=redisCache.getCacheObject(getPhoneKey(phone));
        if (StringUtils.isEmpty(code)){
            return AjaxResult.error("验证码已过期");
        }
        if (StringUtils.isEmpty(verificationCode)){
            return AjaxResult.error("验证码未填写");
        }
        if (!code.equals(verificationCode.trim())){
            return AjaxResult.error("验证码验证不正确");
        }
        return AjaxResult.success("验证码验证正确");
    }


    private String getPhoneKey(String phone){
        return VALIDATION+":"+phone;
    }

    // 生成指定长度的验证码的方法
    private String generateVerificationCode(int codeLength) {
        // 定义验证码字符集
        String codeChars = "0123456789";
        // 使用StringBuilder来拼接验证码
        StringBuilder verificationCode = new StringBuilder();
        // 创建Random对象
        Random random = new Random();
        // 循环生成指定长度的验证码
        for (int i = 0; i < codeLength; i++) {
            // 从字符集中随机选择一个字符
            char randomChar = codeChars.charAt(random.nextInt(codeChars.length()));
            // 将选定的字符追加到验证码中
            verificationCode.append(randomChar);
        }

        // 返回生成的验证码字符串
        return verificationCode.toString();
    }
}
